using Digitalmes.Domain.Entities.Mes.Productions;
using Digitalmes.Domain.Entities.Mes.Reworks;

namespace Digitalmes.Application.Mes.Reworks.Doc.Commands;

/// <summary>
/// 取消返工工单命令。
/// </summary>
public sealed record CancelReworkDocCommand(long RewordDocId) : IRequest<IResult<bool>>;

internal sealed class CancelReworkDocCommandHandler(IRepository<ReworkDoc> repo, IRepository<ProdCurrentState> wipRepo) : IRequestHandler<CancelReworkDocCommand, IResult<bool>>
{
    public async Task<IResult<bool>> Handle(CancelReworkDocCommand request, CancellationToken cancellationToken)
    {
        var doc = await repo.GetByIdAsync(request.RewordDocId, cancellationToken);
        if (doc == null)
        {
            return Result.Failure("返工单不存在");
        }

        // 仅处于创建状态的返工单才可以取消
        if (doc.Status != ReworkStatusEnum.Created)
        {
            return Result.Failure("返工单已开始执行，不能取消");
        }

        doc.Status = ReworkStatusEnum.Cancel;
        var ok = await repo.UpdateAsync(doc, m => new
        {
            m.Status,
        }, cancellationToken);

        // 重置产品返工单
        var wip = await wipRepo.FirstOrDefaultAsync(m => m.Sn == doc.Sn, cancellationToken);
        if (wip != null)
        {
            wip.InReworkDocId = 0;
            await wipRepo.UpdateAsync(wip, m => new
            {
                m.InReworkDocId,
            }, cancellationToken);
        }

        return Result.From(ok);
    }
}
